package com.xmg.p2p.base.service.impl;

import com.xmg.p2p.base.domain.SystemDictionaryItem;
import com.xmg.p2p.base.domain.UserFile;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.mapper.UserFileMapper;
import com.xmg.p2p.base.query.PageResult;
import com.xmg.p2p.base.query.UserFileQO;
import com.xmg.p2p.base.service.IUserFileService;
import com.xmg.p2p.base.service.IUserinfoService;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserFileServiceImpl implements IUserFileService{
    @Autowired
    private UserFileMapper userFileMapper;
    @Autowired
    private IUserinfoService userinfoService;
    @Override
    public List<UserFile> listByHasType(Long id, boolean hasType) {
        return userFileMapper.listByHasType(id,hasType);
    }

    @Override
    public void apply(String fileName) {
        UserFile uf = new UserFile();
        uf.setImage(fileName);
        uf.setApplier(UserContext.getCurrent());
        uf.setApplyTime(new Date());
        uf.setState(UserFile.STATE_APPLY);
        userFileMapper.insert(uf);
    }

    @Override
    public void batchUpdateFileType(Long[] ids, Long[] fileTypes) {
        for (int i=0;i<ids.length;i++){
            UserFile uf = userFileMapper.selectByPrimaryKey(ids[i]);
            SystemDictionaryItem item = new SystemDictionaryItem();
            item.setId(fileTypes[i]);
            uf.setFileType(item);
            userFileMapper.updateByPrimaryKey(uf);
        }
    }

    @Override
    public PageResult query(UserFileQO qo) {
        int count = userFileMapper.queryCount(qo);
        if(count>0){
            return new PageResult(userFileMapper.query(qo),count,qo.getCurrentPage(),qo.getPageSize());
        }
        return PageResult.empty(qo.getPageSize());
    }

    @Override
    public void audit(Long id, int score, String remark, int state) {
        UserFile uf = userFileMapper.selectByPrimaryKey(id);
        if(uf!=null&&uf.getState()==UserFile.STATE_APPLY){
            uf.setAuditor(UserContext.getCurrent());
            uf.setAuditTime(new Date());
            uf.setState(state);
            if(state==UserFile.STATE_PASS){
                uf.setScore(score);
                Userinfo userinfo = userinfoService.get(uf.getApplier().getId());
                userinfo.setScore(userinfo.getScore()+score);
                userinfoService.update(userinfo);
            }
            userFileMapper.updateByPrimaryKey(uf);
        }
    }
}
